#!/usr/bin/env sh

# 选择或输入 Nginx 镜像
Nginx_Image_Selection()
{
  while [ -z "${NGINX_IMAGE}" ]; do
    Echo_Blue "选择 Nginx 镜像(${#NGINX_IMAGES[*]}):"

    # for image in ${NGINX_IMAGES[*]}
    for ((i=0;i<${#NGINX_IMAGES[*]};i++))
    do
      echo "${i}) ${NGINX_IMAGES[i]}"
    done

    read -p "请选择镜像序号, 或输入镜像名称: " NGINX_IMAGE
    echo

    if [[ ${NGINX_IMAGE} =~ ^[0-9]+$ ]]; then
      NGINX_IMAGE=${NGINX_IMAGES[${NGINX_IMAGE}]}
    fi
  done

  # 配置镜像
  Nginx_Config
}

# Nginx 配置
Nginx_Config()
{
  Echo_Green "Nginx 配置:"
  echo "NGINX_IMAGE=${NGINX_IMAGE}"

  # 包名:版本号
  image=${NGINX_IMAGE%%-*}
  repository=${image%:*}
  version=${image#*:}

  # 资源路径
  NGINX_PATH=${DATA_PATH}/${repository}/${version}

  # 镜像命名空间 HTML_PATH
  if [ -z "${HTML_PATH}" ]; then
    CACHE="${DATA_PATH}/site"
    read -p "文档路径(default=${CACHE}): " HTML_PATH
  else
    echo "HTML_PATH=${HTML_PATH}"
  fi
  if [ -z "${HTML_PATH}" ]; then
    HTML_PATH=${CACHE}
  fi

  # HTTP_PORT
  if [ -z "${HTTP_PORT}" ]; then
    CACHE=80
    read -p "HTTP端口(default=${CACHE}): " HTTP_PORT
  else
    echo "HTTP_PORT=${HTTP_PORT}"
  fi
  if [ -z "${HTTP_PORT}" ]; then
    HTTP_PORT=${CACHE}
  fi
  # 检查端口占用情况
  Check_Port ${HTTP_PORT}
  if [ ! -z "${ERROR}" ]; then
    Exit_Confirm
  fi

  # HTTPS_PORT
  if [ -z "${HTTPS_PORT}" ]; then
    CACHE=443
    read -p "HTTPS端口(default=${CACHE}): " HTTPS_PORT
  else
    echo "HTTPS_PORT=${HTTPS_PORT}"
  fi
  if [ -z "${HTTPS_PORT}" ]; then
    HTTPS_PORT=${CACHE}
  fi
  # 检查端口占用情况
  Check_Port ${HTTPS_PORT}
  if [ ! -z "${ERROR}" ]; then
    Exit_Confirm
  fi

  # 确认并保存配置
  Nginx_Config_Confirm
}

# 确认配置
Nginx_Config_Confirm()
{
  confirm="y"
  # read -p "确认配置Y/n: " confirm
  echo -n -e "确认配置\033[4;35mY\033[0m/n: "; read confirm
  if [[ -z "${confirm}" || "${confirm}" == "y" ]]; then
    # 保存全局安装配置
    Nginx_Config_Update
    Echo_Green "Nginx 配置已保存！"
    echo
  else
    # 重置
    NGINX_IMAGE=
    NGINX_PATH=
    HTML_PATH=
    HTTP_PORT=
    HTTPS_PORT=
    echo
    Nginx_Image_Selection
  fi
}

# 更新数据库配置
Nginx_Config_Update()
{
  # install.conf
  sed -i -e "s|NGINX_IMAGE=.*|NGINX_IMAGE=${NGINX_IMAGE}|g;" ${INSTALL_CONF}
  sed -i -e "s|NGINX_PATH=.*|NGINX_PATH=${NGINX_PATH}|g;" ${INSTALL_CONF}
  sed -i -e "s|HTML_PATH=.*|HTML_PATH=${HTML_PATH}|g;" ${INSTALL_CONF}
  sed -i -e "s|HTTP_PORT=.*|HTTP_PORT=${HTTP_PORT}|g;" ${INSTALL_CONF}
  sed -i -e "s|HTTPS_PORT=.*|HTTPS_PORT=${HTTPS_PORT}|g;" ${INSTALL_CONF}

  # docker-compose.yml
  sed -i -e "s|NGINX_IMAGE|${NGINX_IMAGE}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|NGINX_PATH|${NGINX_PATH}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|HTML_PATH|${HTML_PATH}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|HTTP_PORT|${HTTP_PORT}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|HTTPS_PORT|${HTTPS_PORT}|g;" ${DOCKER_COMPOSE_YML}

  # Dockerfile
}